<?php
/**
 * Copyright 2013 Marek Kaszewski
 *
 * This file is part of the JHUB1 Online Community Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

namespace Jhub1_Common\Entity\BO;

use Jhub1_Common\Entity\EndpointValues;
use Jhub1_Common\Entity\Agents;
use Jhub1_Common\Model\SettingsObjects\DateTimeObject;
use Doctrine\ORM\Query;
use Jhub1_Common\Model\Key\UniqueKey;

class EndpointValuesBO extends AbstractBO
{
    private $valuesPO = null;
    private $serviceLocator;

    public function __construct($serviceLocator)
    {
        $this->getEM($serviceLocator);
        $this->serviceLocator = $serviceLocator;
    }

    public function getAgentPO()
    {
        return $this->valuesPO;
    }

    public function insertValue(Agents $agentPO, $name, $value)
    {
        $kg = new UniqueKey($this);
        $this->em->getConnection()->beginTransaction();
        try {
            $valuesPO = new EndpointValues($agentPO);
            $valuesPO->setId($kg->getUUID());
            $valuesPO->setName($name);
            $valuesPO->setValue($value);
            $this->em->persist($valuesPO);
            $this->em->getConnection()->commit();
        } catch (Exception $e) {
            $this->em->getConnection()->rollback();
            $this->em->close();
            throw $e;
        }
        $this->em->flush();
        $this->valuesPO = $valuesPO;
        return $valuesPO;
    }

    public function getAllEndpoints($agentsNameList)
    {
        if (null != $agentsNameList) {
            if (count($agentsNameList) > 0) {
                $qb = $this->em->createQueryBuilder();
                $qb->select('ev')->from('\Jhub1_Common\Entity\EndpointValues', 'ev')
                    ->where('ev.agentUsername = ?0');
                foreach ($agentsNameList as $key => $val) {
                    if ($key != 0) {
                        $qb->orWhere('ev.agentUsername = ?' . $key);
                    }
                }
                $qb->groupBy('ev.name');
                $qb->setParameters($agentsNameList);
                return $qb->getQuery()->getResult(Query::HYDRATE_OBJECT);
            }
        }
        return null;
    }

    public function checkForNewEndpoints($agentsNameList)
    {
        $newSens = array();
        $sensorsArr = $this->getAllEndpoints($agentsNameList);
        if ($sensorsArr != 0) {
            foreach ($sensorsArr as $value) {
                $qb2 = $this->em->createQueryBuilder();
                $qb2->select('e')->from('\Jhub1_Common\Entity\Endpoints', 'e')
                    ->where('e.address = :address');
                $qb2->setParameter('address', $this->getAddress($value));
                $result = $qb2->getQuery()->getArrayResult();
                if (count($result) == 0) {
                    $newSens[$this->getAddress($value)] = $value;
                }
            }
        }
        return $newSens;
    }

    public function getAddress($arrayRecord)
    {
        return $arrayRecord->getName() . '@' . $arrayRecord->getAgent() . '@jhub1online.org';
    }

    public function isPKUnique($primaryKey)
    {
        if(null == $this->em->getRepository('\Jhub1_Common\Entity\EndpointValues')->find($primaryKey)) {
            return true;
        }
        return false;
    }

    public function getServiceLocator()
    {
        return $this->serviceLocator;
    }

    public function getObjectByUUID($uuid)
    {
        return $this->em->getRepository('\Jhub1_Common\Entity\EndpointValues')->find($uuid);
    }
}